package com.future.taskdemo.k8s.controller;

import com.future.taskdemo.k8s.DeploymentDTO;
import com.future.taskdemo.k8s.K8sManager;
import com.future.taskdemo.k8s.ServiceDTO;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class K8sApiController {


    @RequestMapping("/create/namespace")
    public Map<String, String> testNamespace(@RequestBody V1Namespace namespace) {
        Map<String, String> message = new HashMap<>();
        //初始化k8s
        ApiClient apiClient = K8sManager.getApiClient();
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        try {
            V1Namespace result = coreV1Api.createNamespace(namespace, null, null, null);
            message.put("success", "应用命名空间创建成功！");
        } catch (ApiException e) {
            if (e.getCode() == 409) {
                message.put("error", "命名空间已重复！");
            }
            if (e.getCode() == 200) {
                message.put("success", "应用命名空间创建成功！");
            }
            if (e.getCode() == 201) {
                message.put("error", "命名空间已重复！");
            }
            if (e.getCode() == 401) {
                message.put("error", "无权限操作！");
            }
            message.put("error", "应用命名空间创建失败！");
            e.printStackTrace();
        }
        return message;
    }


    @PostMapping("/create/deployments")
    public Map<String, String> createDeployments(@RequestBody DeploymentDTO deploymentDTO) {
        Map<String, String> messages = new HashMap<>();

        // 赋值操作
        V1Deployment deployment = new V1Deployment();
        deployment.setApiVersion("apps/v1");
        deployment.kind("Deployment");

        // 赋值metadata
        V1ObjectMeta objectMeta = new V1ObjectMeta();
        objectMeta.name(deploymentDTO.getMetadata_name());
        objectMeta.namespace(deploymentDTO.getMetadata_namespace());
        Map<String, String> labels = new HashMap<>();
        labels.put("app", "nginx");
        objectMeta.labels(labels);

        // 赋值spec
        V1DeploymentSpec deploymentSpec = new V1DeploymentSpec();

        //赋值spec-selector
        V1LabelSelector selector = new V1LabelSelector();
        Map<String, String> matchLabels = new HashMap<>();
        matchLabels.put("app", "nginx");
        selector.matchLabels(matchLabels);

        //赋值template
        V1PodTemplateSpec templateSpec = new V1PodTemplateSpec();
        V1ObjectMeta metadata = new V1ObjectMeta();
        metadata.labels(labels);
        templateSpec.metadata(metadata);

        // spec-Template下的Spec
        V1PodSpec podSpec = new V1PodSpec();
        // spec-Template-spec-container
        List<V1Container> listContainer = new ArrayList<>();
        V1Container container = new V1Container();
        container.setName(deploymentDTO.getContainers_name());
        container.setImage(deploymentDTO.getContainers_image());
        container.setImagePullPolicy(deploymentDTO.getContainers_imagePullPolicy());

        // spec-Template-spec-container-ports
        List<V1ContainerPort> ports = new ArrayList<>();
        V1ContainerPort v1ContainerPort = new V1ContainerPort();
        v1ContainerPort.setContainerPort(88);
        container.setPorts(ports);

        listContainer.add(container);
        podSpec.setContainers(listContainer);
        templateSpec.setSpec(podSpec);


        deploymentSpec.setReplicas(deploymentDTO.getSpec_replicas());
        deploymentSpec.setTemplate(templateSpec);
        deploymentSpec.setSelector(selector);
        deployment.setMetadata(objectMeta);
        deployment.setSpec(deploymentSpec);

        ApiClient client = K8sManager.getApiClient();
        AppsV1Api apiInstance = new AppsV1Api(client);
        try {
            V1Deployment result = apiInstance.createNamespacedDeployment(objectMeta.getNamespace(), deployment, null, null, null);
            messages.put("success", "工作负载创建成功！");
        } catch (ApiException e) {
            if (e.getCode() == 409) {
                messages.put("error", "工作负载创建已重复！");
            } else if (e.getCode() == 200) {
                messages.put("success", "工作负载创建成功！");
            } else if (e.getCode() == 201) {
                messages.put("error", "工作负载创建已重复！");
            } else if (e.getCode() == 401) {
                messages.put("error", "无权限操作！");
            } else {
                messages.put("error", "工作负载创建失败！");
            }
        }
        return messages;
    }


    @PostMapping("/create/service")
    public Map<String, String> createService(@RequestBody ServiceDTO serviceDTO) {
        Map<String, String> message = new HashMap<>();
        ApiClient client = K8sManager.getApiClient();
        CoreV1Api apiInstance = new CoreV1Api(client);

        //赋值
        V1Service body = new V1Service();
        body.setApiVersion("v1");
        body.setKind("Service");

        V1ObjectMeta objectMeta = new V1ObjectMeta();
        objectMeta.setName(serviceDTO.getMetadata_name());
        objectMeta.setNamespace(serviceDTO.getMetadata_namespace());

        //赋值spec
        V1ServiceSpec serviceSpec = new V1ServiceSpec();
        //spec-type
        serviceSpec.setType(serviceDTO.getSpec_type());
        //spec-ports
        List<V1ServicePort> servicePorts = new ArrayList<>();
        V1ServicePort servicePort = new V1ServicePort();
        servicePort.setPort(serviceDTO.getSpec_ports_port());
        servicePort.setProtocol(serviceDTO.getSpec_ports_protocol());
        servicePort.setTargetPort(new IntOrString(serviceDTO.getSpec_ports_targetPort()));
        servicePorts.add(servicePort);
        serviceSpec.ports(servicePorts);

        // spec-selector
        Map<String, String> selector = new HashMap<>();
        selector.put("app", "nginx");
        serviceSpec.setSelector(selector);

        body.setMetadata(objectMeta);
        body.setSpec(serviceSpec);

        try {
            V1Service result = apiInstance.createNamespacedService(serviceDTO.getMetadata_namespace(), body, null, null, null);
            message.put("success", "工作负载服务创建成功！");
        } catch (ApiException e) {
            if (e.getCode() == 409) {
                message.put("error", "工作负载服务创建已重复！");
            } else if (e.getCode() == 200) {
                message.put("success", "工作负载服务创建成功！");
            } else if (e.getCode() == 201) {
                message.put("error", "工作负载服务创建已重复！");
            } else if (e.getCode() == 401) {
                message.put("error", "无权限操作！");
            } else if (e.getCode() == 400) {
                message.put("error", "后台参数错误！");
            } else if (e.getCode() == 400) {
                message.put("error", "没有命名空间或没有Deployment！");
            } else {
                message.put("error", "工作负载服务创建失败！");
            }
        }
        return message;
    }


    @RequestMapping("/pod/getPod")
    public Map<String, String> testPod() {
        Map<String, String> message = new HashMap<>();
        //初始化k8s
        ApiClient apiClient = K8sManager.getApiClient();
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        try {
            V1PodList list = coreV1Api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null, null);
            List<V1Pod> items = list.getItems();
            for (V1Pod item : items) {
                item.getStatus();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return message;
    }
}